<template>
    <div>
        <el-button type="text" icon="el-icon-back" size="mini" @click="back">返回</el-button>
        <el-row>
            <el-col :span="16">
                <div class="m-alert">
                    <span class="el-icon-info"></span>
                    <div>
                        <div>1、文本、图片、外链图文、小程序都将占用1次机会（若文本为空将不占用），每个客户每天可接受1条群发消息；(现功能只支持群发文本)</div>
                        <div>2、如客户本月已收到4条群发消息本条邀请将不会成功发送</div>
                    </div>
                </div>

                <div class="interspaceH"></div>

                <el-form ref="massTextForm" :model="textForm" label-width="80px">
                    <el-form-item label="选择客户">
                        <el-radio v-model="textForm.clientType" label="1">全部客户</el-radio>
                        <el-radio v-model="textForm.clientType" label="2">筛选客户</el-radio>
                    </el-form-item>

                    <el-form-item v-if="textForm.clientType == '2'">
                        <el-button class="button-new-tag" type="primary" size="small"
                                   @click="chooseMember()">+ 添加成员
                        </el-button>
                        <el-tag :key="emp.id" v-for="emp in textForm.empList" closable :disable-transitions="false"
                                @close="closeTagHandle(emp)">{{ emp.empName }}
                        </el-tag>

                        <el-dialog title="分配客户" :visible.sync="memberVisible" width="60%" :close-on-click-modal="false">
                            <MultipleSelect ref="selectMultipleMember" :listFields="{deptName: '所属部门', empName: '员工名称',}" :dataSource="memberData" type="filter"/>
                            <span slot="footer" class="dialog-footer">
                                <el-button @click="memberVisible = false">取 消</el-button>
                                <el-button type="primary" @click="submitMultipleMember">确 定</el-button>
                            </span>
                        </el-dialog>
                    </el-form-item>

                    <el-form-item label="群发内容" prop="sendContent" :rules="[{ required: true, message: '请输入群发内容', trigger: 'blur' }]">
                        <el-input type="textarea" placeholder="请输入内容" v-model="textForm.sendContent" maxlength="1200"
                                  show-word-limit>
                        </el-input>
                    </el-form-item>
                    <MaterialContentText ref="materialContentText" :disabledAdd="true" :contentType="[2, 3]"/>
                    <el-form-item label="群发时间">
                        <el-radio v-model="textForm.timeType" label="1">立即发送</el-radio>
                        <el-radio v-model="textForm.timeType" label="2">定时发送</el-radio>
                    </el-form-item>
                    <el-form-item v-if="textForm.timeType == '2'">
                        <el-date-picker
                                v-model="textForm.massTextTime"
                                type="datetime"
                                placeholder="选择日期时间">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submit">通知员工发送</el-button>
                        <span style="color:#b6b6b6;margin-left: 20px;">通知员工，向所选客户发送以上消息</span>
                    </el-form-item>
                </el-form>
            </el-col>
            <el-col :span='7' style="margin-left: 30px">
                <iframe :src="'http://wx.zzxapps.com/pages/chat/HM-chat?message=' + textForm.sendContent" frameborder="0"
                        style="width: 300px;height: 560px;"></iframe>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import MultipleSelect from "@/components/list_multiple_select/list_multiple_select"
import MaterialContentText from "@/components/material_content_text/material_content_text"

export default {
    name: "creatMassText",
    components: {
        MultipleSelect,
        MaterialContentText
    },
    data() {
        return {
            memberVisible: false,
            clientTagInputVisible: false,
            clientTagInputValue: '',
            textTagInputValue: '',
            textTagInputVisible: false,
            textForm: {
                textTags: [],
                clientType: '1',
                timeType: '1',
                sendContent: '',
                massTextTime: '',
                empList: []
            },
            memberData: []
        }
    },
    mounted() {

    },
    methods: {
        chooseMember() {
            this.$request("/api/emp/getAllEmp/1_0", {}, "POST").then((data) => {
                this.memberData = data.rows
                this.memberVisible = true
            })
        },
        closeTagHandle(tag) {
            this.textForm.empList.splice(this.textForm.empList.indexOf(tag), 1);
        },
        async submit() {
            let that = this

            let data = that.textForm

            if (data.sendContent == null || data.sendContent == "") {
                that.$message.error("请输入群发内容")
                return
            }

            let chooseTime = that.$moment(data.massTextTime).valueOf() / 1000;
            let nowTime = that.$moment().unix()

            if (chooseTime <= nowTime) {
                that.$message.error("不能选择以前的时间")
                return
            }

            let empDictionary = {}

            let clientList = await that.$request("/api/customers/getClientInfoByParams/1_0", {}, "POST")

            if (data.clientType == 1) {
                clientList.rows.map((item) => {
                    if (empDictionary[item.empId] == null) {
                        empDictionary[item.empId] = [item.externalUserId]
                    } else {
                        empDictionary[item.empId].push(item.externalUserId)
                    }
                })
            } else if (data.clientType == 2) {
                clientList.rows.map((item) => {
                    data.empList.map((empInfo) => {
                        if (empInfo.empId == item.empId) {
                            if (empDictionary[item.empId] == null) {
                                empDictionary[item.empId] = [item.externalUserId]
                            } else {
                                empDictionary[item.empId].push(item.externalUserId)
                            }
                        }
                    })
                })
            }

            let content = this.$refs.materialContentText.getData()

            for (let key in empDictionary) {
                let sendMessage = {
                    "chat_type": "single",
                    "external_userid": empDictionary[key],
                    "sender": key,
                    "text": {
                        "content": data.sendContent
                    },
                    "attachments": []
                }
                if (content != null && content.length > 0) {
                    if (content[0]['material'] != null) {
                        if (content[0]['material']['materialType'] == '1') {
                            sendMessage['attachments'].push({
                                "msgtype": "image",
                                "image": {
                                    "pic_url": content[0]['material']['materialLinksCover']
                                }
                            })
                        } else if (content[0]['material']['materialType'] == '2') {
                            sendMessage['attachments'].push({
                                "msgtype": "link",
                                "link": {
                                    "title": content[0]['material']['materialTitle'],
                                    "picurl": "",
                                    "desc": "",
                                    "url": content[0]['material']['materialAppendices']
                                }
                            })
                        }
                    }
                    if (content[0]['contentType'] == '3') {
                        sendMessage['attachments'].push({
                            "msgtype": "link",
                            "link": {
                                "title": content[0]['linkContent']['linkTitle'],
                                "picurl": "",
                                "desc": "",
                                "url": this.$uri + content[0]['linkContent']['linkAddress']
                            }
                        })
                    }
                }

                let payload = {
                    missionInfoMessage: JSON.stringify(sendMessage),
                    sendEmpId: key,
                    missionName: data.sendContent,
                    taskCorrelationType: '8'
                }
                data.timeType == '1' ? "" : payload['alertTime'] = chooseTime

                await this.$request("/api/task/addTask/1_0", payload, "POST")
            }

            this.$message({
                message: '添加成功',
                type: 'success'
            });
            this.$emit("currentHandle", "list")
        },
        submitMultipleMember() {
            let data = this.$refs.selectMultipleMember.getData();
            this.textForm.empList = data
            this.memberVisible = false
        },
        back() {
            this.$emit("currentHandle", "list")
        }
    }
}
</script>

<style scoped>
.el-icon-info {
    color: #35abff;
    margin-right: 10px;
}

.el-tag {
    margin: 0 0 10px 10px;
}

.input-new-tag {
    width: 90px;
}
</style>
